package com.myblockchain.service.impl;


import com.myblockchain.utility.CryptoUtil;
import com.myblockchain.utility.RSACoder;
import com.myblockchain.service.WalletService;
import com.myblockchain.service.model.Wallet;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author Liu
 */
@Service
public class WalletServiceImpl implements WalletService {

    /**
     * 生成钱包
     * @return
     */
    @Override
    public Wallet generateWallet(){
        Map<String, Object> initKey;
        try {
            initKey = RSACoder.initKey();
            String publicKey = RSACoder.getPublicKey(initKey);
            String privateKey = RSACoder.getPrivateKey(initKey);
            return Wallet.builder()
                    .publicKey(publicKey)
                    .privateKey(privateKey)
                    .build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取钱包地址
     * @return
     */
    @Override
    public String getWalletAddress(String pubKey){
        String publicKeyHash = hashPubKey(pubKey);
        return CryptoUtil.MD5(publicKeyHash);
    }

    /**
     * 生成钱包公钥
     * @param publicKey
     * @return
     */
    @Override
    public String hashPubKey(String publicKey) {
        return CryptoUtil.SHA256(publicKey);
    }


}
